<?php



/**
 * 竞拍Model
 * Enter description here ...
 * @author Admin
 *
 */
class AuctionModel extends CommonModel {
	
	//过滤
	protected $_filter = array(
		'goodsprice'=>array('','price'),
		'realprice'=>array('','price'),
		'costprice'=>array('','price'),
	);
	
	
	

	/**
	 * 更新竞拍状态
	 * Enter description here ...
	 */
	public function updateState(){
		$timenow = time();
		$startmap=array(
			'starttime'=>array('elt',$timenow),
			'endtime'=>array('gt',$timenow),
			'state'=>array('eq',0)
		);
		$this->where($startmap)->setField('state',1);   //更新开始竞拍

		$endmap=array(
			'endtime'=>array('elt',$timenow),
			'state'=>array('eq',0)
		);

		$this->where($endmap)->setField('state',2);   //更新完成竞拍
	}

	
	
	/**
	 * 竞拍结束的生成订单
	 * Enter description here ...
	 */
	public function endState(){
		$endmap = array(
			'state'=>array('eq',2)
		);
		$enddata = $this->where($endmap)->findAll();
		if (!empty($enddata)){
			$this->where($endmap)->setField('state',3);
			
			$this->produceOrder($enddata);
		}
	}
	
	
	
	
	/**
	 * 获取头条推荐竞拍
	 * Enter description here ...
	 */
	/*
	public function getHead(){
		$map = array(
    		'A.state'=>array('eq',1),
    		'A.recommend'=>array('eq',1)
    	);
    	$prefix = C('DB_PREFIX');
    	$data = $this->Table("{$prefix}auction as A")->
					  join("{$prefix}accessory as AC ON A.goods_pic = AC.id")->
					  join("{$prefix}accessory as ACC ON A.agopic = ACC.id")->
					  field('A.*,AC.path,ACC.path as agopath')->where($map)->
					  find();
		return $data;
	}
	*/
	
	
	
	/**
	 * 获取正在竞拍的数据
	 * @see CommonModel::getdata()
	 */
	public function getdata($map,$limit){
		$prefix = C('DB_PREFIX');
		$data = $this->Table("{$prefix}auction as A")->
					   join("{$prefix}accessory_relation as AR ON A.gid = AR.relationid and AR.table='Goods'")->
					   join("{$prefix}accessory as AC on AR.accessoryid = AC.id")->
					   where($map)->field('A.*,AC.thumbnail')->
					   order('A.endtime asc')->group('A.id')->limit($limit)->
					   findAll();
		return $data;
	}
	
	
	/**
	 * 获取推荐(今天、明天)
	 * Enter description here ...
	 * @param unknown_type $day
	 */
	public function getRecommend($day){
		$prefix = C('DB_PREFIX');
		$timenow = time();
		if ($day == 'today'){
			$s = strtotime(date("Y-m-d 0:0:0",$timenow));
			$e = $s + 86400;
		}elseif ($day == 'tomorrow'){
			$s = strtotime(date("Y-m-d 0:0:0",$timenow+86400));
			$e = $s + 86400;
		}
		$map = array(
			'A.state'=>array('in','0,1'),
			'A.recommend'=>array('eq',1),
			'A.starttime'=>array('between',"{$s},{$e}")
		);
		$data = $this->getdata($map);
		return $data;
	}
	
	
	
	/**
	 * 获取推荐(今天、明天)
	 * Enter description here ...
	 * @param unknown_type $day
	 */
	public function getRecommendNum($day,$limit){
		$prefix = C('DB_PREFIX');
		$timenow = time();
		if ($day == 'today'){
			$s = strtotime(date("Y-m-d 0:0:0",$timenow));
			$e = $s + 86400;
		}elseif ($day == 'tomorrow'){
			$s = strtotime(date("Y-m-d 0:0:0",$timenow+86400));
			$e = $s + 86400;
		}
		$map = array(
			'A.state'=>array('in','0,1'),
			'A.recommend'=>array('eq',1),
			'A.starttime'=>array('between',"{$s},{$e}")
		);
		$data = $this->getdata($map,$limit);
		return $data;
	}
	
	
	
	
	
	
	
	/**
	 * 获取条件ID集  Id1,Id2,...
	 * Enter description here ...
	 * @param unknown_type $map
	 */
	public function getids($map){
		$data = $this->where($map)->field('id')->findAll();
		foreach ($data as $val){
			$tem[] = $val['id'];
		}
		$string = implode(',', $tem);
		return $string;
	}
	
	
	
	
	/**
	 * 获取即将竞拍数据
	 * Enter description here ...
	 * @param unknown_type $map
	 * @param unknown_type $limit
	 */
	public function getFuture($map,$limit){
		$prefix = C('DB_PREFIX');
		$data = $this->Table("{$prefix}auction as A")->
					   join("{$prefix}goods as G on A.gid = G.id")->
					   join("{$prefix}accessory_relation as AR ON A.gid = AR.relationid and AR.table='Goods'")->
					   join("{$prefix}accessory as AC on AR.accessoryid = AC.id")->
					   where($map)->field('A.*,G.goodsbrief,AC.thumbnail')->
					   order('A.starttime asc')->group('A.id')->limit($limit)->
					   findAll();
		return $data;
	}
	
	
	/**
	 * 统计竞拍数
	 * Enter description here ...
	 * @param unknown_type $map
	 */
	public function countNum($map){
		$prefix = C('DB_PREFIX');
		$data = $this->Table("{$prefix}auction as A")->
					   join("{$prefix}goods as G on A.gid = G.id")->
					   where($map)->
					   count();
		return $data;
	}
	
	
	/**
	 * 获取竞拍历史
	 * Enter description here ...
	 * @param unknown_type $map
	 * @param unknown_type $limit
	 */
    public function getHistory($map,$limit){
		$prefix = C('DB_PREFIX');
		$data = $this->Table("{$prefix}auction as A")->
					   join("{$prefix}goods as G on A.gid = G.id")->
					   join("{$prefix}user as U on A.uid = U.id")->
					   join("{$prefix}accessory_relation as AR ON A.gid = AR.relationid and AR.table='Goods'")->
					   join("{$prefix}accessory as AC on AR.accessoryid = AC.id")->
					   where($map)->field('A.*,G.goodsbrief,AC.thumbnail,U.head')->
					   order('A.endtime desc')->group('A.id')->limit($limit)->
					   findAll();
		return $data;
	}
	
	
	
	
	/**
	 * 获取某条竞拍的详细信息
	 * Enter description here ...
	 * @param unknown_type $id
	 */
	public function getOne($id){
		$prefix = C('DB_PREFIX');
		$auctionmap['A.id'] = array('eq',$id);
		$data = $this->Table("{$prefix}auction as A")->
					   join("{$prefix}goods as G on A.gid = G.id")->
					   where($auctionmap)->field('A.*,G.goodsfreight,G.goodsbrief,G.goodsabout')->
					   find();
					   
					     //获取竞拍商品图片附件信息
		$map = array(
			'AR.relationid' => array('eq',$data['gid']),
			'AR.table' => array('eq','Goods')
		);
		
		$accessory = $this->Table("{$prefix}accessory_relation as AR")->
					   join("{$prefix}accessory as AC on AR.accessoryid = AC.id")->
					   where($map)->field('AC.thumbnail,AC.path')->
					   findAll();
		$data['accessory'] = $accessory;
		
		return $data;
	}
	
	
	
	
	
	
	
	
	/**
	 * 生成竞拍订单
	 * Enter description here ...
	 * @param unknown_type $enddata
	 */
	public function produceOrder($enddata){
		$user = D('User');
		$auction_log = D('Auction_log');
		$order = D('Order');
		$insured = M('Insured');
		$goods = D('Goods');
		$config = C('SYSCONFIG');
		
		foreach ($enddata as $val){  //竞拍订单

			if (!empty($val['uid'])){  //竞拍成功人    竞拍表Auction中存放着竞拍成功人相关信息
				do {
					$ordersn = $order->produceSn();   //订单号
				}while (in_array($ordersn, $sn));
				
				$sn[] = $ordersn;
				
				
				$data[] = array(
					'uid'=>$val['uid'],
					'ordersn'=>$ordersn,
					'aid'=>$val['id'],
					'goodsname'=>$val['goodsname'],
					'orderprice'=>$val['realprice'],
					'name'=>$val['auctionuname'],
					'type'=>1,
					'isrebeat'=>0,
					'addtime'=>time()
				);
				
				$winmap['id'] = array('eq',$val['uid']);
				
				$user->where($winmap)->setField('old',1);  //更新用户状态为老用户 （新注册用户未新用户，参与竞拍生订单转换老用户）
			}
			
			
			
			/*
			
			//第二名全额返点
			if($val['rebate'] == 1){
				$rebateauction_logmap = array(
					'aid'=>array('eq',$val['id']),
				);
				//...根据商品竞拍记录获取倒数第二条记录（时间降序，第一条为竞拍成功者，第二条为第二名）
				$rebateauction_logdata = $auction_log->where($rebateauction_logmap)->field('uid')->order('addtime desc')->limit("1,2")->findAll();
				
				$uid4 = $rebateauction_logdata[0]['uid'];
				$name = $user->field('name')->find($uid4);   //用户姓名
				do {
					$ordersn = $order->produceSn();
				}while (in_array($ordersn, $sn));
				
				$sn[] = $ordersn;
				
				//订单金额 = 商品价格 - 实体竞拍币折算金额
				$orderprice = $val['goodsprice'] - $auction_logdata['sumbeat']/$config['rmb_beat'];
				if ($orderprice <= 0){
					$orderprice = $goodsdata['goodsfreight'];   //运费
				}else {
					$orderprice = $orderprice + $goodsdata['goodsfreight'];  //运费  + 订单金额
				}
				
				$data[] = array(
					'uid'=>$uid4,
					'ordersn'=>$ordersn,
					'aid'=>$val['id'],
					'goodsname'=>$val['goodsname'],
					'orderprice'=>$orderprice,
					'name'=>$name['name'],
					'type'=>0,
					'isrebeat'=>1,
					'addtime'=>time()
				);
			}
			
			
			*/
			
			
			//保价订单
			//获取产于竞拍的所有用户id
			$auction_logmap['aid'] = array('eq',$val['id']);
			$auction_logmap['uid'] = array('neq',$val['uid']);
			$auction_logdata = $auction_log->where($auction_logmap)->field('uid')->findAll();   //本竞拍商品所有竞拍人员
			foreach ($auction_logdata as $v){
				$uids1[] = $v['uid'];
			}
			unset($auction_logdata);
			unset($auction_logmap);
			
			
			//获取点击保价的所有用户id
			$insuredmap['aid'] = array('eq',$val['aid']);
			$insuredmap['uid'] = array('neq',$val['uid']);
			$insureddata = $insured->where($insuredmap)->field('uid')->findAll();  //获取竞拍商品报价用户
			foreach ($insureddata as $v){
				$uids2[] = $v['uid'];
			}
			unset($insuredmap);
			unset($insureddata);
			
			
			if (empty($uids1)) $uids1 = array();
			if (empty($uids2)) $uids2 = array();
			$uids = array_merge($uids1, $uids2);
			$uids = array_unique($uids);
			if (empty($uid4)) $uid4 = array();
			$uids = array_diff($uids,$uid4);
			
			
			
			//进行所有用户的保价
			$goodsdata = $goods->field('goodsfreight')->find($val['gid']);   //报价金额
			foreach ($uids as $uid){ 
				$auction_logmap = array(
					'aid'=>array('eq',$val['id']),
					'uid'=>array('eq',$uid)
				);
				
				
				//统计消耗实体币数
				$auction_logdata = $auction_log->where($auction_logmap)->field('sum(beat) as sumbeat')->find();
				//订单金额
				$orderprice = $val['goodsprice'] - $auction_logdata['sumbeat']/$config['rmb_beat'];
				if ($orderprice <= 0){
					$orderprice = $goodsdata['goodsfreight'];  //运费
				}else {
					$orderprice = $orderprice + $goodsdata['goodsfreight'];  //运费+订单金额
				}
				
				$name = $user->field('name')->find($uid);
				
				do {
					$ordersn = $order->produceSn();
				}while (in_array($ordersn, $sn));
				$sn[] = $ordersn;
				
				$data[] = array(
					'uid'=>$uid,
					'ordersn'=>$ordersn,
					'aid'=>$val['id'],
					'goodsname'=>$val['goodsname'],
					'orderprice'=>$orderprice,
					'name'=>$name['name'],
					'type'=>0,
					'isrebeat'=>0,
					'addtime'=>time()
				);
			}
			unset($uids1);
			unset($uids2);
			unset($uids);
			
			
		
			//.....................设置商品竞拍订单过期时间	
			$order_expired = time() + $config['order_expired'] * 86400;   //过期时间
			$this->where($auctionmap)->setField('ordertime',$order_expired);  //设置订单时间
			
			
		}
		
		
		$info = $order->addAll($data);   //生成订单
		
	}
	
	
	
	
	
	
	
	/**
	 * 竞拍第二名虚拟币和实体币返还虚拟币
	 * Enter description here ...
	 * @param unknown_type $data
	 */
	/*
	function fullRebate($data){
		$auction_log = D('Auction_log');
		$auction_logmap = array(
			'aid'=>array('eq',$data['id']),
		);
		
		//获取本竞拍第二名竞拍者
		$auction_logdata = $auction_log->where($auction_logmap)->order('addtime desc')->limit("1,2")->findAll();
		$logdata = $auction_logdata[0];
		
		if(!empty($logdata)){
			$user = D('User');
			$userdata = $user->find($logdata['uid']);
			
			if(!empty($userdata)){
				$auction_logmap['uid'] = array('eq',$userdata['id']);    //用户ID
				$beatcount = $auction_log->where($auction_logmap)->sum('beat');    //实体币
				$pointbcount = $auction_log->where($auction_logmap)->sum('pointb');  //虚拟币
				
				$count =$beatcount+$pointbcount;   //实体币和虚拟币总和
				
				if(!empty($count)){
					
					//添加交易日志 -----返还到虚拟币，
					$config = C('SYSCONFIG');
					$transaction = D('Transaction');
					
					//$remark = "竞拍商品{$logdata['goodsname']}第二名全额返点返还{$count}{$config['pointb_name']}";
	    			
	    			$transactiondata = array(
						'uid'=>$userdata['id'],
						'name'=>$userdata['name'],
						'payment'=>'第二名全额返点',
	    				
	    				//.....实体币和虚拟币之和返还实体币 
						//'money'=>0,
	    				//'beat'=>$count,
						//'remark'=>$remark,
	    			
						'money'=>$count,
						'addtime'=>time(),
						'remark'=> "竞拍商品{$logdata['goodsname']}第二名全额返点返还{$count}{$config['pointb_name']}",
						'type'=>"pointb",
						'source'=>'6',
						'robot'=>'0'
	    			
					);
					
					$transaction->insert($transactiondata);
					
					$user->setInc('pointb',"id={$userdata['id']}",$count);    //竞拍币增加到用户虚拟币账户
					
					
					return $userdata['id'];
				}
			}
		}
		
	}
	*/
	
	
	
}
?>